package services

import (
	"errors"
	"hft/Database/admin"
	"hft/global"
)

type Property struct{}

func (*Property) CreateProperty(property *admin.Property) error {

	res := global.OC_DB.Where("name = ?", property.Name).Or("status_code = ?", property.StatusCode).Omit("id").FirstOrCreate(&property)

	if res.Error != nil {
		return errors.New("未知错误500")
	}

	if res.RowsAffected == 0 {
		return errors.New("该状态码或者名称已存在")
	}

	return nil
}

func (*Property) EditProperty(status *admin.Property) error {

	var nowProperty *admin.Property

	if status.ID == 0 {
		return errors.New("无效的操作")
	}

	err := global.OC_DB.First(&nowProperty, status.ID).Error

	if err != nil {
		return errors.New("找不到该状态")
	}

	err = global.OC_DB.Model(&admin.Property{}).Where("id = ?", status.ID).Updates(&admin.Property{
		Name:       status.Name,
		BackColor:  status.BackColor,
		TextColor:  status.TextColor,
		StatusCode: status.StatusCode,
	}).Error

	if err != nil {
		return errors.New("重复的状态码或状态名称")
	}

	return nil
}

func (*Property) GetPropertyList() (list []*admin.Property, err error) {

	var propertyList []*admin.Property

	global.OC_DB.Find(&propertyList)

	return propertyList, nil
}

func (*Property) Delete(ids []int) (err error) {

	var list []*admin.Property

	global.OC_DB.Find(&list, ids)

	global.OC_DB.Model(&admin.Property{}).Unscoped().Delete(&list)

	return nil

}

var PropertyService = new(Property)
